package rsschart.charter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * this functionality is redundant with DOM libaries,
 * but they might be too heavy for the simple needs here.
 * If it makes sense, this code can be replaced by a DOM/XML
 * building library
 * @author Joe Hubert
 *
 */

public class TagUtil {
	
	private String name;
	private Map attribs;
	private String innerXml;
	
	//private boolean closeTag;
	
	public TagUtil() {}

	public TagUtil(String name) {
		this.name = name;
	}
	
	public TagUtil(String name, String innerXml) {
		this.name = name;
		this.innerXml = innerXml;
	}
	
	public TagUtil(String name, Map attribs) {
		this.name = name;
		this.attribs = attribs;
	}
	
	public TagUtil(String name, Map attribs, String innerXml) {
		this.name = name;
		this.attribs = attribs;
		this.innerXml = innerXml;
	}
	
	
	public void addAttrib(String attrib, String val) {
		if (attribs==null) {
			attribs = new HashMap();
		}
		attribs.put(attrib, val);
	}
	
	public String write() {
		return write(false);
	}
	
	public String write(boolean closeTag) {
		StringBuffer tag = new StringBuffer();
		Iterator atts;
		String attrib;
		String val;
		
		tag.append("<"+ name);
		if (!(attribs == null || attribs.isEmpty())) {
			atts = attribs.keySet().iterator();
			while (atts.hasNext()) {
				attrib = (String)atts.next();
				tag.append(" " + attrib +"=\"");
				tag.append((String)attribs.get(attrib) + "\"");
			}
			if (closeTag) {
				if (innerXml==null) {
					tag.append(" />");
				}
				else {
					tag.append(">");
					tag.append(innerXml);
					tag.append(close());
				}
			}
			else {
				tag.append(" >");
			}
		}
		return tag.toString();
	}
	
	public String close() {
		return "</" + name + ">";
	}
	
	public String getInnerXml() {
		return innerXml;
	}

	
	

	public static void main(String[] args) {
		
		TagUtil tag1;
		TagUtil tag2;
		
		tag1 = new TagUtil("rect");
		tag1.addAttrib("x", "100");
		tag1.addAttrib("y", "200");
		tag1.addAttrib("height", "300");
		tag1.addAttrib("width", "400");
		
		System.out.println(tag1.write(true));
		
		tag2 = new TagUtil("text", "Pets that Jenny Wants");
		tag2.addAttrib("x", "100");
		tag2.addAttrib("y", "200");
		tag2.addAttrib("text-anchor", "middle");
		tag2.addAttrib("font-size", "11");

		System.out.println(tag2.write(true));
		
		
		
	}
	
	

}
